package com.rcl.himalaya_kotlin.fragment

import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import com.rcl.himalaya_kotlin.R
import com.rcl.himalaya_kotlin.`interface`.IRecommendViewCallback
import com.rcl.himalaya_kotlin.adapter.RecommendAdapter
import com.rcl.himalaya_kotlin.presenter.RecommendPresenter
import com.rcl.himalaya_kotlin.utils.UIUtil
import com.ximalaya.ting.android.opensdk.model.album.Album

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2020/9/2.
 * PS: Not easy to write code, please indicate.
 */
class RecommendFragment : Fragment(), IRecommendViewCallback {

    private var recommendAdapter: RecommendAdapter? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val fmview: View = inflater.inflate(R.layout.fragment_recommend, container, false)
        initRecycler(fmview)

        RecommendPresenter.registerViewCallback(this)
        RecommendPresenter.getRecommendList()

        return fmview
    }

    private fun initRecycler(view: View) {
        val recycler: RecyclerView = view.findViewById(R.id.mRecyclerView)
        recycler.layoutManager = LinearLayoutManager(context)
        //设置RecyclerView item间距
        //设置RecyclerView item间距
        recycler.addItemDecoration(object : ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                outRect.top = UIUtil.dip2px(view.context, 5.0)
                outRect.bottom = UIUtil.dip2px(view.context, 5.0)
                outRect.left = UIUtil.dip2px(view.context, 5.0)
                outRect.right = UIUtil.dip2px(view.context, 5.0)
            }
        })
        recommendAdapter = RecommendAdapter()
        recycler.adapter = recommendAdapter
    }

    override fun onRecommendListLoaded(result: List<Album>) {
        //把数据s设置给适配器，并且更新ui
        recommendAdapter?.setData(result)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        RecommendPresenter.unRegisterViewCallback(this)
    }
}